package com.bwie.system.service.impl;

import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.*;
import com.bwie.common.domain.request.ChargeStationReq;
import com.bwie.common.domain.request.CollectReq;
import com.bwie.common.domain.request.CommentReq;
import com.bwie.common.domain.response.ChargeStationRes;
import com.bwie.common.domain.response.CommentRes;
import com.bwie.common.redis.service.RedisService;
import com.bwie.common.result.PageResult;
import com.bwie.common.utils.JwtUtils;
import com.bwie.system.mapper.ChargeStationMapper;
import com.bwie.system.service.ChargeStationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @ClassName: ChargeStationServiceImpl
 * @Description:
 * @Author: ZengFz
 * @Date: 2024/5/17 11:24:03
 */
@Service
public class ChargeStationServiceImpl implements ChargeStationService {

    @Autowired
    private ChargeStationMapper chargeStationMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private HttpServletRequest request;

    @Override
    public List<City> cityList() {
        return chargeStationMapper.cityList();
    }

    @Override
    public PageResult<ChargeStationRes> chargeStationList(ChargeStationReq chargeStationReq) {
        PageHelper.startPage(chargeStationReq.getPageNum(), chargeStationReq.getPageSize());
        List<ChargeStationRes> chargeStationList = chargeStationMapper.chargeStationList(chargeStationReq);
        PageInfo<ChargeStationRes> info = new PageInfo<>(chargeStationList);
        return PageResult.toPageResult(info.getTotal(),chargeStationList);
    }

    /**
     * 字典值存储 Redis
     * @return
     */
    @Override
    public List<ChargeStationType> chargeStationTypeList() {
        String redisKey = "typeList";
        List<ChargeStationType> cacheList = redisService.getCacheList(redisKey);
        if (!cacheList.isEmpty()){
            return cacheList;
        }else {
            List<ChargeStationType> chargeStationTypeList = chargeStationMapper.chargeStationTypeList();
            redisService.setCacheList(redisKey,chargeStationTypeList);
            return chargeStationTypeList;
        }
    }

    @Override
    public void updChargeStationType(ChargeStationType chargeStationType) {
        String redisKey = "typeList";
        chargeStationMapper.updChargeStationType(chargeStationType);
        redisService.deleteObject(redisKey);
        List<ChargeStationType> chargeStationTypeList = chargeStationMapper.chargeStationTypeList();
        redisService.setCacheList(redisKey,chargeStationTypeList);
    }

    @Override
    public Integer countStation() {
        User userJson = getUser();
        return chargeStationMapper.countStation(userJson.getUserId());
    }

    @Override
    public void upCollect(CollectReq collectReq) {
        User userJson = getUser();
        if (collectReq.getCollectStatus() == 0){
            //实现站点的收藏接口，注意不能重复收藏
            Integer collect = chargeStationMapper.findCollect(userJson.getUserId(), collectReq.getChargeStationId());
            if (collect != 0){
                throw new RuntimeException("所选站点已收藏，不能重复收藏");
            }
            chargeStationMapper.insert(userJson.getUserId(),collectReq.getChargeStationId());
        }
        //取消收藏
        if (collectReq.getCollectStatus() == 1){
            chargeStationMapper.delCollect(userJson.getUserId(),collectReq.getChargeStationId());
        }

    }

    @Override
    public void userAddCar(CarInfo carInfo) {
        if (!validate(carInfo.getCarNum())){
            throw new RuntimeException("车牌号格式不正确");
        }
        User userJson = getUser();
        carInfo.setUserId(userJson.getUserId());
        Integer count = chargeStationMapper.findCarInfoById(userJson.getUserId());
        if (count == 0){
            carInfo.setCarDefault(0);
        }
        carInfo.setCarDefault(1);
        chargeStationMapper.userAddCar(carInfo);
        delUser();
    }

    @Override
    public void userDelCar(Integer carId) {
        User userJson = getUser();
        chargeStationMapper.userDelCar(userJson.getUserId(),carId);
        delUser();
    }

    /**
     * 修改车辆信息
     * @param carInfo
     */
    @Override
    public void userUpdCar(CarInfo carInfo) {
        User userJson = getUser();
        carInfo.setUserId(userJson.getUserId());
        //可以把某一辆车设置为默认
        chargeStationMapper.userUpdCar(carInfo);
        delUser();
    }

    @Override
    public List<CommentRes> commentList() {
        return chargeStationMapper.commentList();
    }

    @Override
    public void updComment(CommentReq commentReq) {
        chargeStationMapper.updComment(commentReq);
    }

    private boolean validate(String carNum) {
        Pattern compile =
                Pattern.compile("/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/");
        return compile.matcher(carNum).matches();
    }

    /**
     * 封装一个 获取用户信息的方法
     * @return
     */
    private User getUser(){
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        Object userJson = redisService.getCacheObject(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return (User) userJson;
    }

    /**
     * 封装一个 删除用户信息的方法
     * @return
     */
    private void delUser(){
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        redisService.deleteObject(TokenConstants.LOGIN_TOKEN_KEY + userKey);
    }
}
